package com.gitee.common.data.tree.node;

import java.util.Arrays;

public abstract class MoreNextTreeItemNodeImpl extends AbstractTreeItemNode implements MoreNextTreeItemNodeI {

    private TreeItemNodeI[] nexts;
    private int nextCap = 3;

    @Override
    public int getNextLength() {
        return nexts == null ? 0 : nexts.length;
    }

    @Override
    public TreeItemNodeI[] getNexts() {
        return nexts;
    }

    @Override
    public void changeNext(TreeItemNodeI older, TreeItemNodeI newer) {
        if (nexts != null) {
            TreeItemNodeI node = fetchInNexts(older);
            node = newer;
        }
    }

    @Override
    public void append(TreeItemNodeI next) {
        if (next == null) {
            return ;
        }
        if (fetchInNexts(next) != null ) {
            return ;
        }
        if (nexts == null) {
            nexts = new TreeItemNodeI[nextCap];
        } else {
            if (nexts.length >= nextCap) {
                nexts = Arrays.copyOf(nexts, nextCap * 2);
            }
        }

        nexts[nexts.length] = next;
    }

    @Override
    public void setNextCap(int nextCap) {
        if (nextCap >= 0) {
            this.nextCap = nextCap;
        }
    }

    @Override
    public TreeItemNodeI searchNext(String id) {
        if (nexts == null || id == null) {
            return null;
        }
        for (TreeItemNodeI next : nexts) {
            if (id.equals(next.getId())) {
                return next;
            }
            if (next instanceof NextTreeItemNodeI) {
                return ((NextTreeItemNodeI) next).searchNext(id);
            }
        }
        return null;
    }

    @Override
    public void deleteNext(TreeItemNodeI node) {
        if (node != null && this.nexts != null) {
            TreeItemNodeI nodeI = fetchInNexts(node);
            nodeI = null;
        }
    }

    protected TreeItemNodeI fetchInNexts(TreeItemNodeI nodeI) {
        if (nexts == null) {
            return null;
        }
        for (TreeItemNodeI node : nexts) {
            if (node.compareTo(nodeI) == 0) {
                return node;
            }
        }
        return null;
    }
}
